package com.example.micro.netty.server.nio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClientDemo1 {

    public static void main(String[] args) throws IOException, InterruptedException {

        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        //设置非阻塞
        socketChannel.configureBlocking(false);

        InetSocketAddress in = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(in)) {
            //如果连接不成功

            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间，客户端不会阻塞，可以做其他工作...");
            }

        }

        //...如果连接成功，就发送数据
        String str = "hello boluo!";
        //包裹一个字节数组到Buffer中
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        //为了测试同一个Channel两次想Server端写入数据，是否是同一hashcode
        ByteBuffer byteBuffer2 = ByteBuffer.wrap(str.getBytes());

        //发送数据，将buffer写入channel
        socketChannel.write(byteBuffer);
//        Thread.sleep(5000);
        socketChannel.write(byteBuffer2);
        System.in.read();

    }

}
